package city.spring.utils;

import lombok.Getter;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;

/**
 * 应用上下文静态方法
 *
 * @author HouKunLin
 * @date 2020/8/12 0012 10:24
 */
@Getter
@Component
public class ApplicationContextHolder implements ApplicationContextAware {
    /**
     * 应用上下文对象
     */
    private static ApplicationContext applicationContext;

    public ApplicationContextHolder(ApplicationContext applicationContext) {
        ApplicationContextHolder.applicationContext = applicationContext;
    }

    /**
     * 获取Bean对象
     *
     * @param tClass 对象类型
     * @param <T>    泛型
     * @return 对象
     */
    @Nullable
    public static <T> T getBean(Class<T> tClass) {
        if (applicationContext == null) {
            return null;
        }
        return applicationContext.getBean(tClass);
    }

    @Override
    public void setApplicationContext(@Nullable ApplicationContext applicationContext) throws BeansException {
        ApplicationContextHolder.applicationContext = applicationContext;
    }
}
